import {
  qryPkgInfo,
  adjustPkgInventory,
  qryCustomerStockPkg,
  qryPkgAdjustRecord
} from "@/config/request/opsWms";
import { useAntdTable } from "ahooks";
import { ColumnsType } from "antd/es/table";
import {
  Form,
  Row,
  Col,
  Input,
  Space,
  Button,
  Table,
  Modal,
  Image,
  message,
} from "antd";
import { useFormModal } from "@/hooks/useFormModal";
import { useState } from "react";
import "./index.scss";

const opsWms = () => {
  //列表
  const [form] = Form.useForm();
  const columns: ColumnsType<any> = [
    {
      title: "批次包编码",
      dataIndex: "pkgCode",
      key: "pkgCode",
    },
    // {
    //   title: "批次包类型",
    //   dataIndex: "pkgType",
    //   key: "pkgType",
    //   render: (text) => {
    //     const pkgTypeList = {
    //       1: "正品",
    //       2: "次品",
    //       3: "异常",
    //       4: "异常上报采购",
    //     } as const;
    //     return pkgTypeList[text] || "-";
    //   },
    // },
    {
      title: "图片",
      key: "productImg",
      dataIndex: "productImg",
      render: (text) => {
        return <Image src={text} width={100} preview />;
      },
    },
    {
      title: "商品SKU",
      dataIndex: "shopProductSku",
      key: "shopProductSku",
    },
    {
      title: "平台SKU",
      dataIndex: "productSku",
      key: "productSku",
    },
    {
      title: "客户名称",
      dataIndex: "customerName",
      key: "customerName",
    },
    {
      title: "入库数量",
      dataIndex: "amount",
      key: "amount",
    },
    {
      title: "可拣货数量",
      dataIndex: "enablePickNums",
      key: "enablePickNums",
    },
    {
      title: "发货数量",
      dataIndex: "deliveryNums",
      key: "deliveryNums",
    },
    {
      title: "抵扣中数量",
      dataIndex: "deductioningNums",
      key: "deductioningNums",
      render: (text) => {
        return (
          <span style={{color: 'red',fontWeight: 'bold'}}>{ text || 0 }</span>
        )
      }
    },
    {
      title: "仓库",
      dataIndex: "warehouseName",
      key: "warehouseName",
    },
    {
      title: "所在库区",
      dataIndex: "actualRegionName",
      key: "actualRegionName",
    },
    {
      title: "操作",
      fixed: "right",
      key: "action",
      render: (_: any, render: any) => {
        return (
          <>
            <Button
              type="text"
              danger
              onClick={() => {
                openFormUseModal(_);
              }}
            >
              调整库存
            </Button>
            <Button
              type="text"
              onClick={() => {
                openLog(_);
              }}
            >
              调整日志
            </Button>
          </>
        );
      },
    },
  ];
  const { tableProps, search } = useAntdTable(
    async () => {
      const params = {
        ...form.getFieldsValue(),
      };
      const res = await qryCustomerStockPkg(params);
      return {
        total: res.data?.total ?? 0,
        list: res.data?.data ?? [],
      };
    },
    { defaultPageSize: 10, form, manual: true }
  );

  //调整库存
  const formUseModal = useFormModal();
  const [inventoryFrom] = Form.useForm();
  const [editData, setEditData] = useState<any>();
  const [dynNums, setDynNums] = useState<any>()
  const inventoryReg = /^[0-9]\d*$/
  const openFormUseModal = (_) => {
    qryPkgInfo({
      pkgCode: _.pkgCode,
    }).then((res) => {
      const data = res.data.data
      setEditData(data);
      setDynNums('-')
      formUseModal.modal.open();
    });
  };
  const submit = async () => {
    try {
      const values = await inventoryFrom.validateFields();
      adjustPkgInventory({
        ...values,
        pkgCode: editData.pkgCode,
        sourceEnablePickNums: editData.enablePickNums,
      }).then((res) => {
        message.success("编辑成功");
        search.submit();
        formUseModal.modal.close();
      }).catch((res)=>{
        message.error(res);
      });
    } catch (errorInfo) {
    }
  };
  const targetEnablePickNumsChange = () => {
    const num = editData?.enablePickNums + editData?.deliveryNums - (inventoryFrom.getFieldsValue().targetEnablePickNums || 0) 
    setDynNums(num)
  }

  //日志
  const formLog = useFormModal();
  const logColumns: ColumnsType<any> = [
    {
      title: "调整类型",
      dataIndex: "bizType",
      key: "bizType",
      render: (text) => {
        const bizTypeList = {
          1: "增加",
          2: "减少",
        } as const;
        return bizTypeList[text] || "-";
      },
    },
    {
      title: "操作内容",
      dataIndex: "content",
      key: "content",
    },
    {
      title: "关联工单",
      dataIndex: "bizNo",
      key: "bizNo",
    },
    {
      title: "调整原因",
      dataIndex: "reason",
      key: "reason",
      render: (text) => {
        return <div className="reasonBox" title={ text }>{ text }</div>
      }
    },
    {
      title: "操作人",
      dataIndex: "operator",
      key: "operator",
    },
    {
      title: "操作时间",
      dataIndex: "operationTime",
      key: "operationTime",
    }
  ];
  const { tableProps: logTableProps, search: logSearch } = useAntdTable(
    async () => {
      const params = {
        pkgCode: editData?.pkgCode
      };
      const res = await qryPkgAdjustRecord(params);
      return {
        total: res.data?.total ?? 0,
        list: res.data?.data ?? [],
      };
    },
    { defaultPageSize: 10, form, manual: true }
  );
  const openLog = (_) => {
    qryPkgInfo({
      pkgCode: _.pkgCode,
    }).then((res) => {
      const data = res.data.data
      setEditData(data);
      formLog.modal.open();
      logSearch.submit()
    });
  };
  return (
    <div className="bg-white p-2.5 opsWms">
      <Form form={form} name="supplierList_search">
        <Row>
          <Col span={4}>
            <Form.Item label="批次包编码" name="pkgCode">
              <Input placeholder="请输入" allowClear />
            </Form.Item>
          </Col>
          <Col span={3}>
            <Form.Item label="订单编号" name="platformOrderNo">
              <Input placeholder="请输入" allowClear />
            </Form.Item>
          </Col>
          <Col span={4}>
            <Form.Item label="主账号ID" name="mainCustomerId">
              <Input placeholder="请输入" allowClear />
            </Form.Item>
          </Col>
          <Col span={3}>
            <Form.Item label="子账号ID" name="customerId">
              <Input placeholder="请输入" allowClear />
            </Form.Item>
          </Col>
          <Col span={4}>
            <Form.Item label="客户名称" name="customerName">
              <Input placeholder="请输入" allowClear />
            </Form.Item>
          </Col>
          <Col span={4}>
            <Form.Item label="平台SKU" name="productSku">
              <Input placeholder="请输入" allowClear />
            </Form.Item>
          </Col>
          <Col span={3}>
            <Form.Item label="商品SKU" name="shopProductSku">
              <Input placeholder="请输入" allowClear />
            </Form.Item>
          </Col>
          <Col span={7} style={{ textAlign: "right" }}>
            <Form.Item>
              <Space size="small">
                <Button
                  type="primary"
                  htmlType="submit"
                  onClick={search.submit}
                >
                  搜索
                </Button>
                <Button type="primary" onClick={search.reset}>
                  重置
                </Button>
                <span style={{color: '#7f7f7f'}}>只展示单一客户的成品囤货库存</span>
              </Space>
            </Form.Item>
          </Col>
        </Row>

        <Table
          {...tableProps}
          bordered
          columns={columns}
          rowKey="pkgCode"
          locale={{ emptyText: "暂无数据" }}
          scroll={{ x: "calc(0vw + 10px)" }}
        />
      </Form>
      <Modal
        width={800}
        className="formOpsWmsModal"
        destroyOnClose
        open={formUseModal.isOpen}
        onOk={() => {
          submit();
        }}
        onCancel={() => {
          formUseModal.modal.close();
        }}
        title={"调整库存"}
        okText="确定"
        cancelText="取消"
        maskClosable={false}
      >
        <Form form={inventoryFrom} name="inventoryFrom" layout="horizontal">
          <div className="editDataBox">
            <div>sku总库存数量:{editData?.checked}</div>
            <div>sku已冻结数量:{editData?.freezed}</div>
            <div>调整前可拣货数量:{editData?.enablePickNums}</div>
            <div>调整前发货数量:{editData?.deliveryNums}</div>
          </div>
          <Form.Item
            rules={[{ required: true, message: "请输入正确的调整后可拣货数量", pattern: inventoryReg }]}
            label="调整后可拣货数量"
            name="targetEnablePickNums"
          >
            <Input placeholder="请输入" allowClear onChange={targetEnablePickNumsChange}/>
          </Form.Item>
          <Form.Item label="调整后发货数量">{ isNaN(dynNums) ? '-' : dynNums }</Form.Item>
          <Form.Item
            rules={[{ required: true, message: "调整原因不能为空" }]}
            label="调整原因"
            name="reason"
            required
          >
            <Input.TextArea placeholder="请输入" maxLength={100} />
          </Form.Item>
          <Form.Item
            rules={[{ required: true, message: "关联工单不能为空" }]}
            label="关联工单"
            name="bizNo"
            required
          >
            <Input placeholder="请输入" allowClear maxLength={100} />
          </Form.Item>
        </Form>
      </Modal>
      
      <Modal
        width={800}
        className="formLog"
        destroyOnClose
        open={formLog.isOpen}
        onOk={() => {
          formLog.modal.close();
        }}
        onCancel={() => {
          formLog.modal.close();
        }}
        title={"调整日志"}
        okText="确定"
        cancelText="取消"
        maskClosable={false}
      >
        <Table
          {...logTableProps}
          bordered
          columns={logColumns}
          rowKey="pkgCode"
          locale={{ emptyText: "暂无数据" }}
          scroll={{ x: "calc(0vw + 10px)" }}
        />
      </Modal>
    </div>
  );
};

export default opsWms;
